package com.chanel.iamframework.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.NotNull;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chanel.iamframework.core.dao.RoleDAO;
import com.chanel.iamframework.core.domain.Group;
import com.chanel.iamframework.core.domain.Role;
import com.chanel.iamframework.core.service.RoleService;

public class RoleServiceImpl implements RoleService {

	private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
	
	private RoleDAO roleDAO;
	
	public RoleServiceImpl(@NotNull RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	
	@Override
	public Role getRole(Long roleId) {
		return roleDAO.getRole(roleId);
	}

	@Override
	public void createRole(Role role) {
		roleDAO.createRole(role);
	}

	@Override
	public boolean updateRole(Role role) {
		return roleDAO.updateRole(role) > 0 ? true : false;
	}

	@Override
	public boolean deleteRole(Long roleId) {
		return roleDAO.deleteRole(roleId) > 0 ? true : false;
	}

	@Override
	public Role loadGroups(Long roleId) {
		return roleDAO.loadGroups(roleId);
	}

	@Override
	public Role loadApplications(Long roleId) {
		return roleDAO.loadApplications(roleId);
	}

	@Override
	public Role loadUsers(Long roleId) {
		return roleDAO.loadUsers(roleId);
	}

	@Override
	public void addGroups(Role role) {
		if (CollectionUtils.isEmpty(role.getGroups())) {
			logger.debug("role.groups is empty");
		} else {
			logger.debug("role.groups contain {} groups", role.getGroups().size());
			for (Group group: role.getGroups()) {
				roleDAO.addGroup(group.getGroupId(), role.getRoleId());
				logger.debug("association ({}, {}) created", role, group);
			}
		}
	}

	@Override
	public boolean deleteGroups(Role role) {
		boolean deletedGroups = false;
		
		if (CollectionUtils.isEmpty(role.getGroups())) {
			logger.debug("role.groups is empty");
		} else if (roleDAO.getRole(role.getRoleId()) == null) {
			logger.debug("roleId={} not exist", role.getRoleId());
		} else {
			List<Group> groupsToBeDeleted = new ArrayList<Group>();
			
			logger.debug("role.groups contain {} groups", role.getGroups().size());
			for (Group group: role.getGroups()) {
				if (roleDAO.deleteGroup(group.getGroupId(), role.getRoleId()) > 0) {
					groupsToBeDeleted.add(group);
					logger.debug("association ({}, {}) deleted", role, group);
				} else {
					logger.debug("association ({}, {}) not found", role, group);
				}
			}
			
			role.getGroups().removeAll(groupsToBeDeleted);
			deletedGroups = groupsToBeDeleted.size() > 0;
		}
		
		return deletedGroups;
	}

}
